import { _decorator, BlockInputEvents, CCString, Component, EventTarget, NodeEventType, RichText, ScrollView, UITransform } from 'cc';
import { Logger } from 'db://assets/util';
import { EventType, STATE, TIMER } from 'db://assets/enum';
import { ServiceLocator } from '../service';
import { nextFrameExecute, yieldToMain } from "run-time-opti";
import { throttle } from 'radash';
const { ccclass, menu, property } = _decorator;

@ccclass('Printer')
@menu('tools/Printer')
export class Printer extends Component {
    #logger = new Logger('打印机::Printer')
    #service = ServiceLocator;

    @property(ScrollView)
    content: ScrollView

    @property(RichText)
    context: RichText

    @property(CCString)
    printerStr: string

    get #events() {
        return this.#service.get<EventTarget>(STATE.EVENT)
    }

    get UI() {
        return this.getComponent(UITransform)
    }

    get contextUI() {
        return this.context.getComponent(UITransform)
    }

    get contentUI() {
        return this.content.getComponent(UITransform)
    }

    $ended = false;

    protected onEnable(): void {
        this.#logger.debug("#onEnable")
        this.content.node.on(NodeEventType.TOUCH_START, throttle({ interval: TIMER.THROTTLE }, this.onTouch), this)
        this.context.string = ''
        this.$ended = false
    }

    protected onDisable(): void {
        this.#logger.debug('#onDisable')
        this.context.string = ''
        this.content.node.off(NodeEventType.TOUCH_START)
    }

    onTouch = () => {
        this.#logger.debug('点击了打印')
        this.print()
    }

    printAnime() {
        this.#logger.debug('开始打印动画')
        this.#logger.debug('打印内容', this.printerStr)
        this.#logger.debug('当前内容', this.context.string)
        this.context.string = ''
        this.schedule(() => {
            this.context.string += this.printerStr[this.context.string.length]
            if (this.contextUI.height > this.contentUI.height) {
                this.content.scrollToBottom(0.2)
            }
            if (this.context.string.length == this.printerStr.length) {
                this.#logger.debug('对话打印结束')
                this.ended()
            }
        }, 0.02, this.printerStr.length - 1)
    }

    async print() {
        this.#logger.debug('立即打印', this.$ended)
        if (this.$ended) return this.#events.emit(EventType.NEXT_FRAME)
        this.unscheduleAllCallbacks()
        this.context.string = this.printerStr
        requestAnimationFrame(() => {
            this.content.scrollToBottom(0.2)
        })
        await nextFrameExecute(() => {
            this.ended()
        })
    }

    ended() {
        this.#logger.debug('打印结束')
        this.#events.emit(EventType.FRAME_END)
        this.getComponent(BlockInputEvents).enabled = false
        this.$ended = true
    }
}

